package com.weifly.weistock.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author weifly
 * @since 2019/1/27
 */
public class WeistockUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 相乘
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double multi(double d1, double d2){
        BigDecimal b1 = new BigDecimal(String.valueOf(d1));
        BigDecimal b2 = new BigDecimal(String.valueOf(d2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 想除
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double divide(double d1, double d2){
        BigDecimal b1 = new BigDecimal(String.valueOf(d1));
        BigDecimal b2 = new BigDecimal(String.valueOf(d2));
        return b1.divide(b2, 6, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 相加
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double add(double d1, double d2){
        BigDecimal b1 = new BigDecimal(String.valueOf(d1));
        BigDecimal b2 = new BigDecimal(String.valueOf(d2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 相减
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double subtract(double d1, double d2){
        BigDecimal b1 = new BigDecimal(String.valueOf(d1));
        BigDecimal b2 = new BigDecimal(String.valueOf(d2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 转为json字符串
     *
     * @param obj
     * @return
     */
    public static String toJsonString(Object obj){
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 转为json对象
     *
     * @param jsonStr
     * @return
     */
    public static <T> T toJsonObject(String jsonStr, Class<T> type){
        try {
            return mapper.readValue(jsonStr, type);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
